package com.huilian.tool.douyin.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.common.config.DouYinConfig;
import com.huilian.tool.common.utils.HuiLianHttpUtil;
import com.huilian.tool.douyin.dto.CertificateDto;
import com.huilian.tool.douyin.web.service.CommonService;
import com.huilian.tool.douyin.web.service.DouYinLiFeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 抖音本地生活服务商服务类
 *
 * @Author 少凡
 * @Date 2022-12-08 20:49
 * version 1.0
 */
@Slf4j
@Service
public class DouYinLiFeServiceImpl implements DouYinLiFeService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DouYinConfig douYinConfig;
    @Resource
    private CommonService commonService;

    //该接口用于获取接口调用的凭证 client_token。该接口适用于抖音授权。
    @Override
    public JSONObject getClientToken() {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/oauth/client_token/");
        Map<String, Object> params = new HashMap<>();
        params.put("client_key", douYinConfig.getIotboxLifeAppid());
        params.put("client_secret", douYinConfig.getIotboxLifeSecret());
        params.put("grant_type", "client_credential");
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);
        String result = restTemplate.postForObject(url.toString(), entity, String.class);
        return commonService.unifiedReturn(result);
    }

    @Override
    public JSONObject shopPoiQuery(Map<String, Object> params, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/shop/poi/query/");
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);
        System.err.println(reqUrl);
        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject shopPoiUpdate(Map<String, Object> params, String accessToken) {
        return null;
    }


    /**
     * 验券准备
     * 抖音团购券码的核销, 需要先调用本接口, 查询订单的券列表，选择要验的券，再调用验券接口，核销券码
     *
     * @param certificateDto
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject verifyPrepare(CertificateDto certificateDto, String accessToken) {

        Map<String, Object> params = new HashMap<>();

        //如果有传短网址进来，表示是扫码核卡的
        if (!StringUtils.isBlank(certificateDto.getShortUrl())) {
            log.warn("抖音核销走shortUrl");

            RestTemplate tempRest = new RestTemplate(new SimpleClientHttpRequestFactory() {
                @Override
                protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
                    connection.setInstanceFollowRedirects(false);
                }
            });

            ResponseEntity<String> response = tempRest.exchange(certificateDto.getShortUrl(), HttpMethod.GET, null, String.class);


            String location = response.getHeaders().getLocation() == null ? "" : response.getHeaders().getLocation().toString();


            //获取到重定向长链接
            if (location.length() > 0) {
                //截取object_id与后面第一个&的值
                String str1 = location.substring(location.indexOf("object_id") + 10, location.length());
                String objectId = str1.substring(0, str1.indexOf("&"));
                params.put("encrypted_data", objectId);

            }
        } else {
            params.put("code", certificateDto.getCode());
            log.warn("抖音核销走code");
        }
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/fulfilment/certificate/prepare/");
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    /**
     * 验券
     * 用于核销券码，同时适用于抖音团购券码与三方券码
     *
     * @param verifyToken
     * @param poiId
     * @param encryptedCodes
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject verifyCertificate(String verifyToken, String poiId, String encryptedCodes, String accessToken) {
        log.info("verifyToken：" + verifyToken);
        log.info("poiId：" + poiId);
        log.info("encryptedCodes：" + encryptedCodes);
        log.info("accessToken：" + accessToken);

        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/fulfilment/certificate/verify/");
        Map<String, Object> params = new HashMap<>();
        params.put("verify_token", verifyToken);
        params.put("poi_id", poiId);
        params.put("encrypted_codes", new String[]{encryptedCodes});
        return commonService.PostRequest(url.toString(), accessToken, params);
    }


    /**
     * 撤销核销
     * 用于撤销核销状态
     *
     * @param verifyId
     * @param certificateId
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject verifyCancel(String verifyId, String certificateId, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/fulfilment/certificate/cancel/");
        Map<String, Object> params = new HashMap<>();
        params.put("verify_id", verifyId);
        params.put("certificate_id", certificateId);
        return commonService.PostRequest(url.toString(), accessToken, params);
    }


    /**
     * 券状态查询
     * 用于查询抖音券状态。
     *
     * @param encryptedCode
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject getCertificate(String encryptedCode, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/fulfilment/certificate/get/");
        Map<String, Object> params = new HashMap<>();
        params.put("encrypted_code", encryptedCode);
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    /**
     * 券状态批量查询
     * 用于批量查询抖音券码和三方券码的状态。
     *
     * @param certificateDto
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject certificateQuery(CertificateDto certificateDto, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/fulfilment/certificate/query/");
        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isBlank(certificateDto.getEncryptedCode())) {
            params.put("encrypted_code", certificateDto.getEncryptedCode());
        } else {
            params.put("order_id", certificateDto.getOrderId());
        }
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);
        return commonService.getRequest(reqUrl, accessToken);
    }


    /**
     * 验券历史查询
     * 用于查询验券记录
     *
     * @param certificateDto
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject certificateVerifyRecordQuery(CertificateDto certificateDto, String accessToken) {
        return null;
    }


    /**
     * 分账明细查询
     * 用于查询分账明细
     *
     * @param certificateIds
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject ledgerQueryRecordByCert(List<String> certificateIds, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/settle/ledger/query_record_by_cert/");

        Map<String, Object> params = new HashMap<>();
//        params.put("certificate_ids", certificateDto.getAccountId());
//        params.put("cursor", certificateDto.getCursor());
//        params.put("size", certificateDto.getSize());
//        params.put("bill_date", certificateDto.getBillDate());

        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);

        return commonService.getRequest(reqUrl, accessToken);
    }


    /**
     * 账单详细查询
     * 商家通过接口查询自己账单详情。。
     *
     * @param certificateDto
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject ledgerDetailedQuery(CertificateDto certificateDto, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/settle/ledger/detailed_query/");

        Map<String, Object> params = new HashMap<>();
        params.put("account_id", certificateDto.getAccountId());
        params.put("cursor", certificateDto.getCursor());
        params.put("size", certificateDto.getSize());
        params.put("bill_date", certificateDto.getBillDate());
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);

        return commonService.getRequest(reqUrl, accessToken);
    }


    /**
     * 账单查询
     * 商户通过接口查询账单
     *
     * @param certificateDto
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject ledgerQuery(CertificateDto certificateDto, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/settle/ledger/query/");

        Map<String, Object> params = new HashMap<>();
        params.put("account_id", certificateDto.getAccountId());
        params.put("cursor", certificateDto.getCursor());
        params.put("size", certificateDto.getSize());
        params.put("bill_date", certificateDto.getBillDate());

        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);

        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject supplierMatch(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/poi/v2/supplier/match/";
        return commonService.PostRequest(url, accessToken, params);
    }

    @Override
    public JSONObject supplierQueryTask(String supplierTaskIds, String accessToken) {
        String url = douYinConfig.getUrl() + "/poi/v2/supplier/query/task/?supplier_task_ids=" + supplierTaskIds;
        return commonService.getRequest(url, accessToken);
    }

    @Override
    public JSONObject goodEditProduct(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/product/save/";
        return commonService.PostRequest(url, accessToken, params);
    }

    @Override
    public JSONObject goodGetTemplate(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/template/get/";
        String reqUrl = HuiLianHttpUtil.buildUrl(url, params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject goodGetCategory(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/category/get/";
        String reqUrl = HuiLianHttpUtil.buildUrl(url, params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject goodQueryOnlineProduct(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/product/online/query/";
        String reqUrl = HuiLianHttpUtil.buildUrl(url, params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject goodsSyncStock(Map<String, Object> params, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/stock/sync/";
        return commonService.PostRequest(url, accessToken, params);
    }

    @Override
    public JSONObject partnerQuery(String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/partner/order/query/";
        Map<String, Object> params = new HashMap<>();
        return commonService.PostRequest(url, accessToken, params);
    }

    @Override
    public JSONObject partnerCreate(String accountId, String accessToken) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/partner/order/create/";
        Map<String, Object> params = new HashMap<>();
        params.put("account_id", accountId);
        params.put("cooperation_content", 5);
        LocalDateTime date = LocalDateTime.now();
        date = date.plusMinutes(5);
        params.put("start_time", date.toEpochSecond(ZoneOffset.of("+8")));
        date = date.plusYears(1).minusDays(1);
        params.put("end_time", date.toEpochSecond(ZoneOffset.of("+8")));
        params.put("charge_type", 2);
        return commonService.PostRequest(url, accessToken, params);
    }

    /**
     * 订单查询
     *
     * @param params
     * @param accessToken
     * @return
     */
    @Override
    public JSONObject tradeOrderQuery(Map<String, Object> params, String accessToken) {
        StringBuilder url = new StringBuilder(douYinConfig.getUrl()).append("/goodlife/v1/trade/order/query/");
        String reqUrl = HuiLianHttpUtil.buildUrl(url.toString(), params);
        return commonService.getRequest(reqUrl, accessToken);
    }

    @Override
    public JSONObject goodQueryOnlineProduct(String accessToken, String accountId) {
        String url = douYinConfig.getUrl() + "/goodlife/v1/goods/product/online/query/";

        Map<String, Object> params = new HashMap<>();
        //页数,第一页不传
//        params.put("cursor", cursor);
        params.put("count", "50");
        params.put("account_id", accountId); // 商家ID，传入时服务商须与该商家满足授权关系
        /*
         * 区分商品创建者的查询方式
         * 0 - 查询服务商/开发者创建的商品
         * 1 - 查询商家（account_id）创建的商品
         */
        params.put("goods_creator_type", 1);
        params.put("status", 1); // 过滤在线状态 1-在线 2-下线 3-封禁

        String reqUrl = HuiLianHttpUtil.buildUrl(url, params);
        return commonService.getRequest(reqUrl, accessToken);
    }


}
